/******************************************************************************************************
Copyright (C) 2013 Mestrelab Research S.L. All rights reserved.

This file is part of the MNova scripting toolkit.

Authorized users of MNova Software may use this file freely, but this file is provided AS IS
with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE.
*****************************************************************************************************/

/*globals FileDialog, MessageBox, Dir, settings, print, getMaskFiles, dbOpenDatabase, DBPlugin, Resumable, ProgressDialog, serialization, qsTr, Application, dbMakeDBItems, MnUi*/
/*jslint plusplus: true, indent: 4*/

function dbImportDocuments() {
	"use strict";
	var dir, files, dbname, dbDef, resumable, progress, startTime, s, ok, canceled,
		fileCount, f, file, dw, startTimeDoc, dbItems, cid,
		fileMask = "*.mnova", // This mask specifies files to be processed.
		dirMask = "*", // This mask specifies subdirectories to be scanned.
		dirSettingsKey = "Database/Import Documents/Last Directory",
		resumeSettingsKey = "Database/Import Documents/Resume",
	// Prompt for directory
		dirName = FileDialog.getExistingDirectory(settings.value(dirSettingsKey, Dir.home()), qsTr("Select Directory"));

	if (!dirName) {
		return;
	}
	dir = new Dir(dirName);
	if (!dir.exists) {
		return MessageBox.critical(qsTr("Directory '{0}' does not exist.").format(dirName));
	}
	dir.cdUp();
	settings.setValue(dirSettingsKey, dirName);

	// Get documents to import
	print("Searching for files in " + dirName + "...");

	files = getMaskFiles(dirName, dir.absPath, fileMask, dirMask, true);
	if (files.length <= 0) {
		return MessageBox.critical(qsTr("Could not find any files for processing in directory '{0}'.").format(dirName));
	}
	print("Found " + files.length + " files to process.");
	//MessageBox.information ("Found " + files.length + " files to process.");

	// Choose database
	dbname = dbOpenDatabase();
	if (!dbname) {
		return;
	}

	dbDef = DBPlugin.client.definition(dbname);

	// Show resume dialog
	resumable = new Resumable(resumeSettingsKey, 1, files.length, qsTr("Import Documents"));
	resumable.dialogMessage = qsTr("Found <b>{0}</b> documents for import into database <b>{1}</b>.").format(files.length, dbname);
	if (!resumable.init()) {
		return;
	}
	// Show progress dialog
	progress = new ProgressDialog();
	progress.setRange(0, files.length);
	progress.show();

	// Process documents
	startTime = new Date();
	print("It is now " + startTime.toString());
	s = serialization;
	s.fileHistory = false;

	ok = true;
	canceled = false;
	fileCount = 0;
	for (f = resumable.minValue - 1; f < resumable.maxValue && !canceled && !progress.wasCanceled; ++f) {
		file = files[f];

		// Update progress dialog
		progress.value = f;
		progress.labelText = qsTr("Importing document {0} of {1}...\n{2}").format(f - resumable.minValue + 2, resumable.maxValue - resumable.minValue + 1, file);

		// Update resumable
		resumable.setValue(f + 1);

		// If there has been an error on previous save causing the server to close the connection, ask user for stop or continue
		if (!ok) {
			if (MessageBox.question(qsTr("Continue with Import?"), MessageBox.Yes, MessageBox.No) === MessageBox.Yes) {
				if (!DBPlugin.client.connected()) {
					Application.mainWindow.doAction("dbConnect");
				}
			} else {
				canceled = true;
			}
		}
		ok = !canceled && DBPlugin.client.connected();
		if (ok) {
			print("Opening file " + f + ": " + file);
			if (s.open(file)) {
				dw = Application.mainWindow.activeDocument;
				print(" Opened ok: " + dw.itemCount() + " items.");
				startTimeDoc = new Date();
				dbItems = dbMakeDBItems(DBPlugin.client, dbDef, true, false);
				cid = 0;
				try {
					// addRecord may throw exception on empty dbItems (User canceled save in dbPreSaveHook)
					cid = DBPlugin.addRecord(DBPlugin.client, dbItems);
					print("Saved " +  dbItems.length + " items to record " + cid + " in " + ((new Date() - startTimeDoc) / 1000) + " seconds.");
					fileCount++;
				} catch (err) {
					MessageBox.critical(qsTr("Error while saving '{0}'.").format(file));
					ok = false;
				}
				dw.close();
			} else {
				MessageBox.critical(qsTr("Could not open file '{0}'.").format(file));
				ok = false;
			}
		}
	}
	if (!(canceled || progress.wasCanceled)) {
		resumable.setValue(0);
	}
    progress.close();
    MessageBox.information(qsTr("Imported <b>{0}</b> documents into database <b>{1}</b>.").format(fileCount, dbname));
	print("All done in " + ((new Date() - startTime) / 1000) + " seconds.");
}

if (this.MnUi && MnUi.scripts_db) {
	MnUi.scripts_db.scripts_db_ImportDocuments = dbImportDocuments;
}
